package com.wephone.Student.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.easemob.exceptions.EaseMobException;
import com.loopj.android.http.RequestParams;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.media.UMImage;
import com.wephone.Student.BaseApplication;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.RegisterResponse;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.MD5;
import com.wephone.Student.util.ShareReferenceUtil;
import com.wephone.Student.util.Util;

public class NewRegisterActivity3 extends BaseActivity {
	private ViewFlipper viewFlipper;
	private int liuxueIdx;
	private String uPlatform;
	private String uPlatformid;
	private String gender;
	private String username;
	private String password;
	private String nick;
	private int _year;
	private int _month;
	private int _day;
	private String signature;
	private String photoSavedPath = null;
	public static int uLocType = -1;
	public static String uLocDetail = "";
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_register_3);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			uPlatform = bundle.getString("uPlatform");
			uPlatformid = bundle.getString("uPlatformid");
			gender = bundle.getString("gender");
			username = bundle.getString("username");
			password = bundle.getString("password");
			nick = bundle.getString("nick");
			signature = bundle.getString("signature");
			_year = bundle.getInt("year");
			_month = bundle.getInt("month");
			_day = bundle.getInt("day");
			photoSavedPath = bundle.getString("photoSavedPath");
		}
		init();
	}

	private void init() {
		viewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
		viewFlipper.addView(getSubView1());
		viewFlipper.addView(getSubView2());

		findViewById(R.id.btn_back).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (liuxueIdx != 0) {
							liuxueIdx = 0;
							viewFlipper.setInAnimation(getApplicationContext(),
									R.anim.slide_in_from_left);
							viewFlipper.setOutAnimation(
									getApplicationContext(),
									R.anim.slide_out_to_right);
							viewFlipper.showPrevious();
						} else {
							finish();
						}
					}
				});
		
	}

	private MyResponseHandler getHandler() {
		MyResponseHandler handler = new MyResponseHandler(
				NewRegisterActivity3.this, RegisterResponse.class) {
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);

				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				if (getDataSuccess) {
					RegisterResponse res = (RegisterResponse) response;
					BaseActivity.infoData = res.getData();
					ShareReferenceUtil.saveUserId(getApplicationContext(), res
							.getData().getuId());
					// setAliasAndTags(ShareReferenceUtil.getUserId(getApplicationContext()));
					String infoJson = gson.toJson(res.getData());
					ShareReferenceUtil.saveUserInfoJson(
							getApplicationContext(), infoJson);
					File photoSavedFile = new File(photoSavedPath);
					if (photoSavedFile != null && photoSavedFile.exists()) {
						photoSavedFile.delete();
					}
					// reg push
					RequestParams params = new RequestParams();
					params.put("uId",
							BaseActivity.getMyInfo(getApplicationContext())
									.getuId());
					params.put("uPushIdentifier", ShareReferenceUtil
							.getUserPushId(getApplicationContext()));
					HttpClient.getInstance().get(Constants.API_REG_PUSH_URL,
							params, getHandler2());

					// login huanxin account
					EMChatManager.getInstance().login(infoData.getuId(),
							infoData.getuPwd(), new EMCallBack() {
								@Override
								public void onError(int arg0,
										final String errorMsg) {
									runOnUiThread(new Runnable() {
										public void run() {
											Toast.makeText(
													NewRegisterActivity3.this,
													"登录聊天服务器失败，您将收不到消息",
													Toast.LENGTH_SHORT).show();
										}
									});
								}

								@Override
								public void onProgress(int arg0, String arg1) {
								}

								@Override
								public void onSuccess() {
									// 登陆成功，保存用户名密码
									BaseApplication.getInstance().setUserName(
											infoData.getuId());
									BaseApplication.getInstance().setPassword(
											infoData.getuPwd());
									runOnUiThread(new Runnable() {
										public void run() {
											EMGroupManager.getInstance()
													.loadAllGroups();
											EMChatManager.getInstance()
													.loadAllConversations();

										}
									});
									processContactsAndGroups();
									// try {
									// //
									// demo中简单的处理成每次登陆都去获取好友username，开发者自己根据情况而定
									// List<String> usernames =
									// EMChatManager.getInstance().getContactUserNames();
									// System.out.println("-----usernames.size()-----"+usernames.size());
									// Map<String, User> userlist = new
									// HashMap<String, User>();
									// for (String username : usernames) {
									// User user = new User();
									// user.setUsername(username);
									// setUserHearder(username, user);
									// userlist.put(username, user);
									// }
									// // 添加user"新的朋友"
									// User newFriends = new User();
									// newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
									// newFriends.setNick("新的朋友");
									// newFriends.setHeader("");
									// userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);

									// List<String> userNameList =
									// EMChatDB.getInstance().findAllParticipantsWithMsg();
									// for(String userName:userNameList){
									// User newFriends = new User();
									// newFriends.setUsername(userName);
									// newFriends.setNick("nick"+userName);
									// newFriends.setHeader("");
									// userlist.put(Constant.NEW_FRIENDS_USERNAME,newFriends);
									// }

									// //添加"群聊"
									// // User groupUser = new User();
									// //
									// groupUser.setUsername(Constant.GROUP_USERNAME);
									// // groupUser.setNick("群聊");
									// // groupUser.setHeader("");
									// // userlist.put(Constant.GROUP_USERNAME,
									// groupUser);
									//
									// //存入内存
									// BaseApplication.getInstance().setContactList(userlist);
									// // 存入db
									// UserDao dao = new
									// UserDao(MainActivity.this);
									// List<User> users = new
									// ArrayList<User>(userlist.values());
									// dao.saveContactList(users);
									//
									// // 获取群聊列表,sdk会把群组存入到EMGroupManager和db中
									// EMGroupManager.getInstance().getGroupsFromServer();
									// } catch (Exception e) {
									// e.printStackTrace();
									// }

									// EMChat.getInstance().setAppInited();
								}
							});
					// 登录分享
					UMSocialService mController = UMServiceFactory
							.getUMSocialService("com.umeng.share");
					if (uPlatform != null) {
						if (uPlatform.equals("sina")) {
							mController
									.setShareContent(Constants.LOGIN_SHARE_TEXT);
							mController.setShareMedia(new UMImage(
									getApplicationContext(),
									R.drawable.login_share_image));
							mController.directShare(getApplicationContext(),
									SHARE_MEDIA.SINA, new SnsPostListener() {
										@Override
										public void onStart() {
											// Toast.makeText(getApplicationContext(),
											// "分享开始",Toast.LENGTH_SHORT).show();
										}

										@Override
										public void onComplete(
												SHARE_MEDIA platform,
												int eCode,
												SocializeEntity entity) {
											if (eCode == StatusCode.ST_CODE_SUCCESSED) {
												// Toast.makeText(getApplicationContext(),
												// "分享成功",Toast.LENGTH_SHORT).show();
											} else {
												// Toast.makeText(getApplicationContext(),
												// "分享失败",Toast.LENGTH_SHORT).show();
											}
										}
									});
						}
						// else if(uPlatform.equals("qq")){
						// mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
						// mController.setShareMedia(new
						// UMImage(getApplicationContext(),
						// R.drawable.login_share_image));
						// mController.directShare(getApplicationContext(),
						// SHARE_MEDIA.TENCENT,new SnsPostListener() {
						// @Override
						// public void onStart() {
						// // Toast.makeText(getApplicationContext(),
						// "分享开始",Toast.LENGTH_SHORT).show();
						// }
						//
						// @Override
						// public void onComplete(SHARE_MEDIA platform,int
						// eCode, SocializeEntity entity) {
						// if(eCode == StatusCode.ST_CODE_SUCCESSED){
						// // Toast.makeText(getApplicationContext(),
						// "分享成功",Toast.LENGTH_SHORT).show();
						// }else{
						// // Toast.makeText(getApplicationContext(),
						// "分享失败",Toast.LENGTH_SHORT).show();
						// }
						// }
						// });
						// }else if(uPlatform.equals("weixin")){
						// mController.setShareContent(Constants.LOGIN_SHARE_TEXT);
						// mController.setShareMedia(new
						// UMImage(getApplicationContext(),
						// R.drawable.login_share_image));
						// mController.directShare(getApplicationContext(),
						// SHARE_MEDIA.WEIXIN,new SnsPostListener() {
						// @Override
						// public void onStart() {
						// // Toast.makeText(getApplicationContext(),
						// "分享开始",Toast.LENGTH_SHORT).show();
						// }
						//
						// @Override
						// public void onComplete(SHARE_MEDIA platform,int
						// eCode, SocializeEntity entity) {
						// if(eCode == StatusCode.ST_CODE_SUCCESSED){
						// // Toast.makeText(getApplicationContext(),
						// "分享成功",Toast.LENGTH_SHORT).show();
						// }else{
						// // Toast.makeText(getApplicationContext(),
						// "分享失败",Toast.LENGTH_SHORT).show();
						// }
						// }
						// });
						// }
					}

					startActivity(new Intent(getApplicationContext(),
							MainTabBar.class));
					finish();
				}
			}

			@Override
			public void onFailure(Throwable arg0, String result) {
				super.onFailure(arg0, result);

				if (progressDialog != null) {
					progressDialog.dismiss();
				}
				Toast.makeText(getApplicationContext(),
						getString(R.string.network_error_txt),
						Toast.LENGTH_SHORT).show();
			}

		};
		return handler;
	}
	private MyResponseHandler getHandler2(){
		MyResponseHandler handler = new MyResponseHandler(NewRegisterActivity3.this,BaseResponse.class){
			@Override
			public void onSuccess(String result) {
				super.onSuccess(result);
				
//				if(getDataSuccess){
//					
//				}
			}
		};
		return handler;
	}
	private void processContactsAndGroups() {
		// 获取群聊列表(群聊里只有groupid和groupname等简单信息，不包含members),sdk会把群组存入到内存和db中
		try {
			EMGroupManager.getInstance().getGroupsFromServer();
		} catch (EaseMobException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private View getSubView1() {
		final Bundle bundle = new Bundle();
		bundle.putString("uPlatform", uPlatform);
		bundle.putString("uPlatformid", uPlatformid);
		bundle.putString("gender", gender);
		bundle.putString("username", username);
		bundle.putString("password", password);
		bundle.putString("nick", nick);
		bundle.putString("signature", signature);
		bundle.putInt("year", _year);
		bundle.putInt("month", _month);
		bundle.putInt("day", _day);
		bundle.putString("photoSavedPath", photoSavedPath);
		
		View view = getLayoutInflater().inflate(
				R.layout.activity_new_register_3_sub_1, null);
		view.findViewById(R.id.reg_layout_1).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						liuxueIdx = 1;
						/*
						viewFlipper.setInAnimation(getApplicationContext(),
								R.anim.slide_in_from_right);
						viewFlipper.setOutAnimation(getApplicationContext(),
								R.anim.slide_out_to_left);
						viewFlipper.showNext();
						*/
						startActivityForResult(new Intent(getApplicationContext(),MyLocationInfo1Activity.class).putExtras(bundle),1);
					}
				});
		view.findViewById(R.id.reg_layout_2).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						liuxueIdx = 2;
						/*
						viewFlipper.setInAnimation(getApplicationContext(),
								R.anim.slide_in_from_right);
						viewFlipper.setOutAnimation(getApplicationContext(),
								R.anim.slide_out_to_left);
						viewFlipper.showNext();
						*/
						startActivityForResult(new Intent(getApplicationContext(),MyLocationInfo2Activity.class).putExtras(bundle),2);
					}
				});
		view.findViewById(R.id.reg_layout_3).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						liuxueIdx = 3;
						/*
						viewFlipper.setInAnimation(getApplicationContext(),
								R.anim.slide_in_from_right);
						viewFlipper.setOutAnimation(getApplicationContext(),
								R.anim.slide_out_to_left);
						viewFlipper.showNext();
						*/
						startActivityForResult(new Intent(getApplicationContext(),MyLocationInfo3Activity.class).putExtras(bundle),3);
					}
				});
		return view;
	}

	private View getSubView2() {
		View view = getLayoutInflater().inflate(
				R.layout.activity_new_register_3_sub_2, null);
		
		
		return view;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (liuxueIdx != 0) {
				liuxueIdx = 0;
				// viewFlipper.setInAnimation(getApplicationContext(),
				// R.anim.slide_in_from_left);
				// viewFlipper.setOutAnimation(getApplicationContext(),R.anim.slide_out_to_right);
				// viewFlipper.showPrevious();
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
